<?php

/**
 * Description of storeo2o
 *
 * @author libaoling
 * @time 2014-12-5
 */
class Storeo2oModel extends BaseModel
{
    var $table  = 'store_o2o';
    var $prikey = 'store_id';
    var $alias  = 'so';
    var $_name  = 'storeo2o';
    
    var $_relation = array(
        // 店铺和分类是多对多的关系
        'has_scategory' => array(
            'model'         => 'scategory',
            'type'          => HAS_AND_BELONGS_TO_MANY,
            'middle_table'  => 'category_store',
            'foreign_key'   => 'store_id',
            'reverse'       => 'belongs_to_storeo2o',
        ),
        // 店铺有多个推荐
        'has_o2orecommends' => array(
            'model'         => 'o2orecommend',
            'type'          => HAS_MANY,
            'foreign_key'   => 'store_id',
            'dependent'     => true
        ),
        // 一个店铺对应多个商品图片
        'has_o2ogoodsimage' => array(
            'model' => 'o2ogoodsimage',
            'type' => HAS_MANY,
            'foreign_key' => 'store_id',
            'dependent' => true
        ),
        'has_storeo2olang' => array(
            'model' => 'storeo2olang',
            'type' => HAS_MANY,
            'foreign_key' => 'store_id',
            'dependent' => true
        ),
    );
    
    function unique_store_no($store_no, $store_id = 0)
    {
        $conditions = "store_no = '" . $store_no . "'";
        $store_id && $conditions .= " AND store_id <> '" . $store_id . "'";
        return count($this->find(array('conditions' => $conditions))) == 0;
    }
    
    public function get_by_id($store_id)
    {
        $result = $this->findAll(array(
                'conditions' => "store_id = '$store_id'",
                'include' => array('has_storeo2olang' => array( 'index_key' => 'lang')),
            ));
        return $this->remake_stores($result);
    }

    public function remake_stores($stores)
    {
        $result = $stores;
        foreach ($stores as $key => $store)
        {
            if(isset($store['store_o2o_lang']))
            {
                foreach ($store['store_o2o_lang'] as $lang => $value)
                {
                    $result[$key]['store_name'][$value['lang']] = $value['store_name'];
                    $result[$key]['store_name_'.$value['lang']] = $value['store_name'];
                    $result[$key]['products'][$value['lang']] = $value['products'];
                    $result[$key]['products_'.$value['lang']] = $value['products'];
                }
                unset($result[$key]['store_o2o_lang']);
            }
        }
        return $result;
    }
    
}
